package deleteface.bank.jqsoft.cn.deleteface.setip;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;


import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jqsoft.bank.deleteface.R;


//设置服务器
public class SettingServerActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.treatment_title)
    TextView treatment_title;
    public static final int TYPE_MULTIPLE_LINE=2;
    private SettingServerAdapter mAdapter;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.im_add)
    ImageView im_add;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.btn_delete)
    RelativeLayout btn_delete;
    @BindView(R.id.btn_save)
    RelativeLayout btn_save;
    List<SettingServerBean> list;
    private static String CHANGESERVER="1";
    private static String ADDSERVER="2";
    List<SettingServerBean> Serverlist=new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_server);
        ButterKnife.bind(SettingServerActivity.this);
        initView();
        loaddata();

    }




    private void loaddata(){
        Serverlist.clear();
        Serverlist = DataSupport.findAll(SettingServerBean.class);
        String name= "";

        if (Serverlist.size()==0){

        }
//        for (int i=0;i<Serverlist.size();i++){
//            if (Serverlist.get(i).getIsUse().equals("1")){
//
//            }
//        }

        SharedPreferences userSettings = getSharedPreferences("setting", 0);
        int  clearSaveState= userSettings.getInt("ipposition",0);
        if (clearSaveState==0){
            ((SettingServerAdapter) mAdapter).SettingChoose( Serverlist.get(0).getIp(),Serverlist.get(0).getTermip(),Serverlist.get(0).getAddress());

        }else {

//            List<SettingServerBean> settingServerBeans =DataSupport.where(" ip=?  ",clearSaveState).find(SettingServerBean.class);
            List<SettingServerBean> settingServerBeans =DataSupport.findAll(SettingServerBean.class);

            if(settingServerBeans.size()==0){
                ((SettingServerAdapter) mAdapter).SettingChoose( Serverlist.get(0).getIp(),Serverlist.get(0).getTermip(),Serverlist.get(0).getAddress());
            }else {
                ((SettingServerAdapter) mAdapter).SettingChoose( Serverlist.get(clearSaveState).getIp(),Serverlist.get(clearSaveState).getTermip(),Serverlist.get(clearSaveState).getAddress());
                MoveToPosition(fullyLinearLayoutManager,clearSaveState);
            }

        }



        mAdapter.setNewData(Serverlist);
        recyclerView.setAdapter(mAdapter);
    }
    /**
     * RecyclerView 移动到当前位置，
     *
     * @param manager  设置RecyclerView对应的manager
     * @param n  要跳转的位置
     */
    public static void MoveToPosition(LinearLayoutManager manager, int n) {
        manager.scrollToPositionWithOffset(n, 0);
        manager.setStackFromEnd(true);
    }
    public void setToolBar(Toolbar toolbar, String title) {
        toolbar.setTitle(title);
        setSupportActionBar(toolbar);
        toolbar.setTitleTextColor(Color.WHITE);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);//显示toolbar的返回按钮
        getSupportActionBar().setDisplayShowHomeEnabled(false);
        View backView = toolbar.findViewById(R.id.ll_back);
        if (backView != null) {
            backView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    //把返回数据存入Intent
                    intent.putExtra("ip", "");
                    intent.putExtra("termip", "");
                    intent.putExtra("address", "");
                    //设置返回数据
                    SettingServerActivity.this.setResult(RESULT_OK, intent);
                    //关闭Activity
                    SettingServerActivity.this.finish();
                }
            });
        }
////        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
////            @Override
////            public void onClick(View view) {
////                onBackPressed();
////            }
////        });
    }
    FullyLinearLayoutManager fullyLinearLayoutManager;
    public void initView() {

        setToolBar(toolbar,"");
        treatment_title.setText("设置服务器");

        srl.setColorSchemeColors(getResources().getColor(R.color.colorTheme));
        srl.setOnRefreshListener(this);


        final BaseQuickAdapter<SettingServerBean, BaseViewHolder> mAdapter = new SettingServerAdapter(new ArrayList<SettingServerBean>(), TYPE_MULTIPLE_LINE,SettingServerActivity.this);
        this.mAdapter = (SettingServerAdapter) mAdapter;
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
         fullyLinearLayoutManager = new FullyLinearLayoutManager(this);
//        new FullyLinearLayoutManager(this)
        recyclerView.setLayoutManager(fullyLinearLayoutManager);
        Util.addDividerToRecyclerView(this, recyclerView, true);
        loaddata();
        mAdapter.setOnItemClickListener(new NoDoubleItemClickListener() {
            @Override
            public void onNoDoubleItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onNoDoubleItemClick(adapter, view, position);

//                SettingServerBean pb = mAdapter.getItem(position);
//                Bundle bundle = new Bundle();
//                    bundle.putSerializable(Constants.SETTING_SERVER_POSTION_ACTIVITY_KEY,   position);
//                bundle.putSerializable(Constants.SETTING_SERVER_ACTIVITY_KEY,   pb);
//                bundle.putSerializable(Constants.SETTING_SERVER_ACTIVITY_STYE_KEY,CHANGESERVER);
//
//                Util.gotoActivityWithBundle(SettingServerActivity.this, SettingServerChangeActivity.class, bundle);
            }
        });

        im_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.SETTING_SERVER_ACTIVITY_STYE_KEY,ADDSERVER);
                Util.gotoActivityWithBundle(SettingServerActivity.this, SettingServerChangeActivity.class, bundle);

            }
        });
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                List<String> iplist1= ((SettingServerAdapter) mAdapter).getIplist();
//                List<String> termiplist1= ((SettingServerAdapter) mAdapter).getTermIplist();
//                List<String> adresslist1= ((SettingServerAdapter) mAdapter).getAdresslist();
//                List<String> iplist = new ArrayList(new TreeSet(iplist1));
//                List<String> termiplist = new ArrayList(new TreeSet(termiplist1));
//                List<String> adresslist = new ArrayList(new TreeSet(adresslist1));
//
//                HashMap<String, Boolean> beans=  ((SettingServerAdapter) mAdapter).getstates();
//                String ip=null;
//                String adress=null;
//                int flag=0;
//                String termip=null;
//                if (beans==null){
//                    Toast.makeText(SettingServerActivity.this,"无数据", Toast.LENGTH_SHORT).show();
//
//                }
//                else {
//                for (int i=0;i<iplist.size();i++){
//
//
//
//                    if ( beans.get(iplist.get(i))){
//                       ip=iplist.get(i);
//                        adress=adresslist.get(i);
//                        termip=termiplist.get(i);
//                        flag=i;
//                   }
//
//                }
//                }
//
                String ip="";
                String adress="";
                String termip="";
                 String finaladress = "";


                List<SettingServerStatesBean> settinglist1= ((SettingServerAdapter) mAdapter).getSettinglist();
                if(settinglist1.size()==0){
                    List<SettingServerBean> settingServerBeans =DataSupport.findAll(SettingServerBean.class);
                    adress=settingServerBeans.get(0).getAddress();
                    ip=settingServerBeans.get(0).getIp();
                    termip=settingServerBeans.get(0).getTermip();
                }else {
                    adress=settinglist1.get(0).getAddress();
                    ip=settinglist1.get(0).getIp();
                    termip=settinglist1.get(0).getTermip();
                }

                final String finalIp = ip;
                final String finaltermIp = termip;
                final String finalAdress = adress;
                Util.showMaterialDialog(SettingServerActivity.this, "提示:", "确定更改ip为"+ip+"(更改成功后，会跳到登录页面重新登录)", "取消", new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                }, "确定", new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        //数据是使用Intent返回
                        Intent intent = new Intent();
                        //把返回数据存入Intent
                        intent.putExtra("ip", finalIp);
                        intent.putExtra("termip", finaltermIp);
                        intent.putExtra("address", finalAdress);
                        //设置返回数据
                        SettingServerActivity.this.setResult(RESULT_OK, intent);
                        //关闭Activity
                        SettingServerActivity.this.finish();



                    }
                }, true);
            }
        });
        btn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<String> iplist1= ((SettingServerAdapter) mAdapter).getIplist();
                final SettingServerBean settingServerBean=  ((SettingServerAdapter) mAdapter).getSettingServerBean();
                List<String> iplist = new ArrayList(new TreeSet(iplist1));
                HashMap<String, Boolean> beans=  ((SettingServerAdapter) mAdapter).getstates();
                String ip=null;

                if (beans==null){
                    Toast.makeText(SettingServerActivity.this,"无数据", Toast.LENGTH_SHORT).show();

                }
                else {
                    for (int i=0;i<iplist.size();i++){

                        if ( beans.get(iplist.get(i))){
                            ip=iplist.get(i);
//                       Toast.makeText(SettingServerActivity.this,"获得"+ip,Toast.LENGTH_SHORT).show();
                        }

                    }
                }
                final String finalIp = ip;

                Util.showMaterialDialog(SettingServerActivity.this, "提示:", "确定删除ip为"+ip+"的服务器数据","取消", new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                }, "确定", new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {


                             DataSupport.deleteAll(SettingServerBean.class,"ip=?", finalIp);
                            Toast.makeText(SettingServerActivity.this,"数据删除成功！", Toast.LENGTH_SHORT).show();
                            onRefresh();

                    }
                }, true);

            }
        });

    }

    private void setRetrofitGlobalUrl(String url){
//        RetrofitUrlManager.getInstance().setGlobalDomain(url);
//        Util.setVariousUrlFromBaseUrl(this, url);
    }



    @Override
    protected void onResume() {

        Serverlist = DataSupport.findAll(SettingServerBean.class);
        mAdapter.setNewData(Serverlist);
        mAdapter.notifyDataSetChanged();
        recyclerView.setAdapter(mAdapter);
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_my_info, menu);
        return super.onCreateOptionsMenu(menu);
    }


    private void exit() {
//        PreferencesUtils.putString(this, Constants.REMEMBERED_USERNAME_KEY, Constants.EMPTY_STRING);
//        PreferencesUtils.putBoolean(this, Constants.WHETHER_REMEMBER_PASSWORD_KEY, false);
//        PreferencesUtils.putString(this, Constants.REMEMBERED_PASSWORD_KEY, Constants.EMPTY_STRING);
//
//
//        RxBus.getDefault().post(Constants.EVENT_TYPE_FINISH_ACTIVITY, true);
//
//        Intent intent = new Intent();
//        intent.setClass(this,LoginActivityNew.class);
//        startActivity(intent);


//        Intent intent = getPackageManager()
//                .getLaunchIntentForPackage(getApplication().getPackageName());
//        PendingIntent restartIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
//        AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
//        mgr.set(AlarmManager.RTC, System.currentTimeMillis() , restartIntent); // 1秒钟后重启应用
//        System.exit(0);


     //   gotoActivity(this, LoginActivityNew.class);


//        RxBus.getDefault().post(Constants.EVENT_TYPE_FINISH_ACTIVITY, true);
//        finish();
//        System.exit(0);


      //  registerFinishActivityEvent();
     /*   finish();
        Util.gotoActivity(getApplicationContext(), LoginActivityNew.class);
        System.exit(0);*/

       /* Intent intent = new Intent(this, LoginActivityNew.class);

        ComponentName cn = intent.getComponent();
        Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);//ComponentInfo{包名+类名}
        startActivity(mainIntent);*/
       /* ActivityManager manager = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
        manager.restartPackage("com.jqsoft.grassroots_civil_administration_platform");
        */


      /*  final Intent intent = new Intent();

        SettingServerActivity.this.stopService(intent);
        System.exit(0);

        ActivityManager am = (ActivityManager) SettingServerActivity.this.getSystemService(SettingServerActivity.this.ACTIVITY_SERVICE);
        am.restartPackage("com.jqsoft.grassroots_civil_administration_platform");
*/
    }

    @Override
    public void onRefresh() {

        loaddata();
        mAdapter.notifyDataSetChanged();
        srl.setRefreshing(false);
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //数据是使用Intent返回
            Intent intent = new Intent();
            //把返回数据存入Intent
            intent.putExtra("ip", "");
            intent.putExtra("termip", "");
            intent.putExtra("address", "");
            //设置返回数据
            SettingServerActivity.this.setResult(RESULT_OK, intent);
            //关闭Activity
            SettingServerActivity.this.finish();


        }
        return super.onKeyDown(keyCode, event);

    }
}
